const axios = require('axios');
const cheerio = require('cheerio');

const index = {
    /**
     * 视频搜索
     * @param {string} keyword 关键词
     */

    search: async (keyword) => {
        const res = await axios.get(`https://search.bilibili.com/video?keyword=${encodeURIComponent(keyword)}`)
        if (res && res.data) {
            return extractVideosData(res.data);
        }
        return null
    }
}

// 视频搜索核心
const extractVideosData = (html) => {
    const $ = cheerio.load(html);
    const data = [];
    // 主体容器搜索
    $('.search-page .video-list-item').each((i, element) => {
        let picture_url = $(element).find('.bili-video-card__cover img').attr('src');

        // 如果图片URL存在，则去掉后缀
        if (picture_url) {
            picture_url = picture_url.split('@')[0]; // 去掉@及其后面的部分
        }
        const anchorElement = $(element).find('.bili-video-card__info--right a');
        const url = anchorElement.attr('href');
        const title = anchorElement.find('h3').attr('title');

        const statsItems = $(element).find('.bili-video-card__mask .bili-video-card__stats--item');
        const views = $(statsItems.get(0)).find('span').last().text();
        const danmuCount = $(statsItems.get(1)).find('span').last().text();

        const author = $(element).find('.bili-video-card__info--author').text();
        const date = $(element).find('.bili-video-card__info--date').text().trim();

        // 构造视频数据对象
        const videoData = {
            picture_url: `https:${picture_url}`,
            url: `https:${url}`, // 确保url是完整的
            title,
            views,
            danmuCount,
            author,
            date: date.replace(/·\s?/, "")
        };

        // 将视频数据添加到数组中
        data.push(videoData);
    });


    return data;
}

module.exports = index